﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using e.Store.DataAccess;
using e.Store.Domain.Repositories;

namespace e.Store.Domain
{
    public class UnitOfWorkcs : IUnitOfWork
    {
        
        private bool _disposed;
        private Hashtable _repositories;
        private eStote_DBEntities _context;

        public UnitOfWorkcs()
        {
            eStote_DBEntities context = new eStote_DBEntities();

            //DbContext(System.Configuration.ConfigurationManager.ConnectionStrings["Entities"].ConnectionString);
            
            if (context == null)
                throw new ArgumentNullException("context");
            _context = context;
        }

        public T ExtRepositoryFor<T>() where T : class
        {
            //return  T();

            return (T)Activator.CreateInstance(typeof(T), _context);
        }

        public IRepository<T> Repository<T>() where T : class
        {
            //  return new Repository<T>(_context);
            if (_repositories == null)
                _repositories = new Hashtable();

            var type = typeof(T).Name;

            if (!_repositories.ContainsKey(type))
            {
                var repositoryType = typeof(Repository<>);
                var repositoryInstance =
                    Activator.CreateInstance(repositoryType
                            .MakeGenericType(typeof(T)), _context);
                _repositories.Add(type, repositoryInstance);
            }

            return (IRepository<T>)_repositories[type];

            // return Activator.CreateInstance(typeof(T));
        }

        public void Save()
        {
            _context.SaveChanges();
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public virtual void Dispose(bool disposing)
        {
            if (!_disposed)
                if (disposing)
                    _context.Dispose();
            _disposed = true;
        }
    }
}
